package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import hello.Device;
import hello.DeviceRepository;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/qdatc") // This means URL's start with /demo (after Application path)
public class MainController {
	@Autowired // This means to get the bean called userRepository
	           // Which is auto-generated by Spring, we will use it to handle the data
	private DeviceRepository deviceRepository;
	
	@GetMapping(path="/add") // Map ONLY GET Requests
	public @ResponseBody String addNewDevice (@RequestParam String name
			, @RequestParam String email) {
		// @ResponseBody means the returned String is the response, not a view name
		// @RequestParam means it is a parameter from the GET or POST request
		
		Device d = new Device();
		d.setName(name);
		d.setEmail(email);
		
		
		
		deviceRepository.save(d);
		
		return "Saved";
	}
	
	@GetMapping(path="/all")
	public @ResponseBody Iterable<Device> getAllUsers() {
		// This returns a JSON or XML with the users
		return deviceRepository.findAll();
	}
	
	@GetMapping(path="/read")
	public @ResponseBody Device find(@RequestParam int id) {
		//Integer ? 如何编写？
		//Long l= new Long(id);
		Device u = (Device)deviceRepository.findOne(new Long(id));
		//userRepository.
		return u;
		
	}
	
}
